<template>
  <div>
    <a-button
      class="marginRight"
      @click="webSocketInit"
      type="primary"
    >
      连接websocket
    </a-button>
    <a-button
      class="marginRight"
      @click="sendMsgTowebSocket"
      type="primary"
    >
      向websocket发送数据
    </a-button>
    <a-button
      @click="handleCloseWebsocket"
      type="primary"
    >
      关闭websocket连接
    </a-button>

    <div>websocket传过来的消息：{{msgFromWebsocket}}</div>
  </div>
</template>

<script>
import { isString } from 'fc-cli-core'
export default {
  name: 'WebsocketPage',
  data() {
    return {
      webSocketObject: null,
      count: 0,
      msgFromWebsocket: '',
    }
  },
  methods: {
    webSocketInit() {
      const webSocketUrl = 'ws://localhost:3000'
      if (this.webSocketObject) return
      this.webSocketObject = new WebSocket(webSocketUrl)
      this.webSocketObject.onopen = this.webSocketOnOpen
      this.webSocketObject.onmessage = this.webSocketOnMessage
      this.webSocketObject.onerror = this.webSocketOnError
      this.webSocketObject.onclose = this.webSocketOnClose
      console.log('this.webSocketObject:', this.webSocketObject)
    },
    handleCloseWebsocket() {
      this.webSocketObject && this.webSocketObject.close()
      this.webSocketObject = null
    },
    sendMsgTowebSocket() {
      this.webSocketObject && this.webSocketObject.send('test 数据' + this.count++)
    },
    webSocketOnOpen(e) {
      console.log('与服务端连接打开->', e)
    },
    webSocketOnMessage(e) {
      console.log('来自服务端的消息->', e)
      console.log('e.data', e.data)
      const msg = e.data

      if (isString(msg)) {
        console.log('msg:', msg)
        this.msgFromWebsocket = msg
      } else if (msg instanceof Blob) {
        const reader = new FileReader()
        reader.readAsText(msg, 'UTF-8')
        reader.onload = () => {
          //字符串和json格式
          //   const result = JSON.parse(reader.result)
          //result = JSON.stringify(reader.result);
          console.log('websocked收到')
          this.msgFromWebsocket = reader.result
        }
      } else {
        let reader = new FileReader()
        reader.readAsText(e.data)
        reader.onload = function () {
          let content = reader.result
          console.log('content:', content)
          this.msgFromWebsocket = content
        }
      }
    },
    webSocketOnError(e) {
      console.log('与服务端连接异常->', e)
    },
    webSocketOnClose(e) {
      console.log('与服务端连接关闭->', e)
    },
  },
}
</script>